<?php

class User_Form_RegisterPersonalNewForm extends Ac_Form
{

    /**
     *
     * @var Model_User empty user with properly setted behavior
     */
    private $_user;

    protected $elementButtonDecorators = array(
        'ViewHelper',
        'Errors',
        //array(array('row' => 'HtmlTag'), array('tag' => 'button'))
       // 'Description'
        //array(array('data' => 'HtmlTag'), array('tag' => 'td', 'class' => 'element')),
        //array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class'=>'button')),
        //array('HtmlTag', array('class' => 'inputText')),
    );

    protected $elementDecorators = array(
        'ViewHelper',
        
       // 'Description'
        //array(array('data' => 'HtmlTag'), array('tag' => 'td', 'class' => 'element')),
        array('Label', array('placement' => 'prepend')),
        array(array('row' => 'HtmlTag'), array('tag' => 'p')),
        //array('Errors', array('tag' => 'span')),
        //array('HtmlTag', array('class' => 'inputText')),
    );

    protected $formDecorators = array(
            'FormElements',
            //array('HtmlTag', array('tag' => 'dl', 'class' => 'zend_form')),
            array('Description', array('placement' => 'prepend')),
            'Form'
    );

    protected $subFormDecorators = array(
        'FormElements',
        //array('HtmlTag', array('tag' => 'dl', 'class' => 'zend_form')),
        array('Description', array('placement' => 'prepend')),
        'fieldset',
    );

    protected $spanDecorators = array(
        'ViewHelper',
        'Errors',
       // 'Description'
        //array(array('data' => 'HtmlTag'), array('tag' => 'td', 'class' => 'element')),
        array('Label', array('placement' => 'prepend')),
        array(array('row' => 'HtmlTag'), array('tag' => 'span')),
        //array('HtmlTag', array('class' => 'inputText')),
    );

    protected $displayGroupDecorators = array(
        'FormElements',
        //array(array('innerHTmlTag' => 'HtmlTag'), array('tag' => 'p', 'class' => 'checkbox'))
        //array('HtmlTag', array('tag' => 'dl')),
    );

    function setUser($user)
    {
        $this->_user = $user;
    }

    protected function newAccount()
    {
        $form = $this->getNewSubForm();
        $form->setDecorators($this->subFormDecorators);
        
        /* Email */
        $form->addElement('text', 'email', array(
            'description' => '请放心，我们不会滥发垃圾邮件',
            'id'      => 'email',
            'name'      => 'email',
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '此信息是必需填写')),
                array('EmailAddress', true, array('messages' => array(Zend_Validate_EmailAddress::INVALID_FORMAT => '請填寫有效電郵地址'))),
            ),
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                            array('Description', array('escape' => false, 'placement' => 'APPEND', 'tag' => 'span', 'class' => 'remark')),
                            array('Label', array('placement' => 'prepend')),
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'email text')),
            ),
            'required'   => true,
            'label'      => '邮箱地址',
        ));

        /* Password */
        $form->addElement('text', 'password', array(
            'id'      => 'password',
            'name'      => 'password',
            'description' => '6-20个字符，不含空格',
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '此信息是必需填写')),
                array('StringLength', true, array(6, 20, 'messages' => '6-20个字符，不含空格')),
            ),
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                            array('Description', array('escape' => false, 'placement' => 'APPEND', 'tag' => 'span', 'class' => 'remark')),
                            array('Label', array('placement' => 'prepend')),
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'password text')),
            ),
            'required'   => true,
            'label'      => '设置密码',
        ));



        /* Username */
        $form->addElement('text', 'username', array(
            'filters'     => array('StringTrim', 'StringToLower'),
            'label'       => '显示的用户名称',
            'id'          => 'username',
            'name'        => 'username',
            'description' => '4-30个字符',
            'validators'  => array(
                array('NotEmpty', true, array('messages' => '此信息是必需填写')),
                //array('Alnum', true, array('messages' => 'Letters and numbers only')),
                array('StringLength', true, array(4, 30, 'messages' => '4-30个字符')),
            ),
            'decorators' => array(
                'ViewHelper',
                'Errors',
                array('Errors', array('id' => 'username_error')),
                array('Description', array('escape' => false, 'placement' => 'APPEND', 'tag' => 'span', 'class' => 'remark')),
                array('Label', array('placement' => 'prepend')),
                array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'username text')),
            ),
            'required'   => true,
        ));
        
        /* Phone */
        $form->addElement('text', 'phone', array(
            'filters'     => array('StringTrim', 'StringToLower'),
            'label'       => '手机号码',
            'id'          => 'phone',
            'name'        => 'phone',
            'description' => '请正确填写您的手机号码，以便买家及时联络您',
            'validators'  => array(
                array('int', false, array('messages' => array(Zend_Validate_Int::NOT_INT =>'請填寫數'))),
            ),
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                            array('Description', array('escape' => false, 'placement' => 'APPEND', 'tag' => 'span', 'class' => 'remark')),
                            array('Label', array('placement' => 'prepend')),
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'phone text')),
            ),            
            'required'   => true,
        ));



        /* Newsletter */
        $form->addElement('checkbox', 'newsletter', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
            ),
            'value' => '1',
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                            array('Label', array('placement' => 'append'), array('class' => 'checkbox')),                           
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'newsletter checkbox')),
            ),
            'label'      => ' 我想收到Maozhao的每月最新情报'
        ));

        /* Submit Button */
        $form->addElement('button', 'register', array(
            'required'    => false,
            'ignore'      => true,
            'type'        => 'submit',
            'label'       => '创建我的账户',
           //'description' => '</div><div class="desc remark">By clicking Create My Account, you agree to AsiaClassified’s <a href="/default/index/term-of-use">Terms of Use</a> and <a href="/default/index/privacy">Privacy Policy</a>.',
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                            array('Description', array('escape' => false, 'placement' => 'APPEND')),
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'button em')),
            ),
        ));
        
        /*Add an hidden input for validators */
        $form->addElement('hidden', 'type', array(
            'validators' => array(
                'Alpha',
            ),
            'value'      => 'personal',
            'required'   => true,
        ));

        $form->getElement('type')->removeDecorator('label');

        $form->getErrors();
        $form->setLegend('');
        $form->addDecorator('fieldset');
        $this->addSubForm($form, 'newaccount');
        
        
    }
    
    public function init()
    {
        parent::init();

        //Choose the method to transfer parameters
        $this->setMethod('post');
        $this->setAction($this->getView()->geturl('register-personal' ,'user'));
        $this->newAccount();

    }
    
    public function isValidPartial(array $post = array())
    {
        $test = parent::isValidPartial($post);
        return $this->validate($post) & $test;
    }
    /**
     *
     * @param array $post
     */
    public function isValid($post = array())
    {
        $test = parent::isValid($post);
        //echo "<pre>";var_dump($this->validate($post), $test);echo "</pre>";exit();
        return $this->validate($post) & $test;
    }
    
    private function validate($post = array())
    {

        $test = true;
        $view = Zend_Registry::get('Zend_View');
        $email = !empty($post['newaccount']['email']) ? $post['newaccount']['email'] : '';
        $confirm_email = !empty($post['newaccount']['confirm_email']) ? $post['newaccount']['confirm_email'] : '';

        //print_r($email);print_r($confirm_email);exit;
        //echo "<pre>";var_dump($post);echo "</pre>";exit();
        //TODO: check if email exists
        if (!empty($post['newaccount']['email']) && !empty($post['newaccount']['confirm_email'])) {
            if (trim($email) != trim($confirm_email)) {
                $this->getSubForm('newaccount')
                        ->getElement('confirm_email')
                        ->addError('電郵地址不符合');
                $test = false;
            }
        }
        
        if (!empty($email)) {
            $num = Model_User::one(array('email' => new MongoRegex('/'.$email.'/i')));
            //echo "<pre>";var_dump($num);echo "</pre>";exit();
            if (!empty($num)) {
                $this->getSubForm('newaccount')
                        ->getElement('email')
                        ->setDisableTranslator(true)
                        ->addError($view->t('__1__已經被使用', null, $email));
                $test = false;
                
            }
        }
        
        //TODO: check if username exists      
        if (!empty($post['newaccount']['username'])) {
            $num = Model_User::one(array('username' => new MongoRegex('/^'.trim($post['newaccount']['username']).'$/i')));
            if (!empty($num)) {
                $this->getSubForm('newaccount')
                        ->getElement('username')
                        ->setDisableTranslator(true)
                        ->addError($view->t('__1__已經被使用', null, $post['newaccount']['username']));
                $test = false;
            }        
        }

        /*if ((!empty($post['newaccount']['password'])) & (!empty($post['newaccount']['confirm_password']))) {
            $password = $post['newaccount']['password'];
            $confirm_password = $post['newaccount']['confirm_password'];

            if (trim($password) != trim($confirm_password)) {
                $this->getSubForm('newaccount')
						->getElement('confirm_password')
						->addError('Passwords do not match');
                $test = false;
            }
        }*/
        
        return $test;        
    }

    /**
     * Save the form when everything is validated
     */
    public function save()
    {
        $res = $this->_user->register($_POST['newaccount']);
/*
        $message = new Model_Message();
        $message->template = 'new-user';
        $message->subject = Zend_Registry::get('Zend_View')->t('Welcome to Asiaclassified!');
        $message->object = 'user';
        //$message->from = ;

        $user = Zend_Registry::get('loggedin_user');
        $message->to = $user->email;

        $message->user = $user;
        $message->sendMessage();
 * 
 */
        $subject = Zend_Registry::get('Zend_View')->t('欢迎注册猫找网!');
        $message = '';

        $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
        //Post an Ad Registration
        if (!empty($to_be_confirmed_ads->arr)) {
            $user = Zend_Registry::get('loggedin_user');
            Ac_Util::sendEmail($subject, $message, $user->email, true, array('user' => $user, 'listing' => Model_Listing::find($to_be_confirmed_ads->arr[0])), Ac_Mail::TEMPLATE_NEWUSER_POSTANAD);
        }
        //Regular Registration
        else {
            $user = Zend_Registry::get('loggedin_user');
            Ac_Util::sendEmail($subject, $message, $user->email, true, array('user' => $user), Ac_Mail::TEMPLATE_NEWUSER);
        }
        $user = Zend_Registry::get('loggedin_user');
        $user -> emailed = '0';
        $user -> l_t = new MongoDate(time());       
        $user -> save();
        return $res;
    }

    private function getNewSubForm()
    {
        $form = new Ac_SubForm();
        //$form->setDecorators($this->subFormDecorators);
        return $form;
    }
}

